package com.zzs.elm.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.zzs.elm.po.Food;
import com.zzs.elm.po.OrderDetailet;
import com.zzs.elm.util.DBUtil;

public class OrderDetailetDao {
	
	public OrderDetailetDao() {
		super();
	}

	private Connection con;
	public OrderDetailetDao(Connection con) {
		super();
		this.con = con;
	}

	private PreparedStatement pst = null;
	private ResultSet rs = null;
	
	public int saveOrderDetailetBatch (List<OrderDetailet> list) throws Exception {
		String sqlTemplate = "insert into orderdetailet(orderId,foodId,quantity) "
				+ "values(?, ?, ?)";
		try {
			int result = 0;
			pst = con.prepareStatement(sqlTemplate);
			for (OrderDetailet orderDetailet : list) {
				pst.setInt(1, orderDetailet.getOrderId());
				pst.setInt(2, orderDetailet.getFoodId());
				pst.setInt(3, orderDetailet.getQuantity());
				result += pst.executeUpdate();
			}
			return result;
		} finally {
			DBUtil.close(rs, pst);
		}
	}
	
	public List<OrderDetailet> listOrderDetailetByOrderId (Integer orderId) throws Exception {
		String sql = "select o.*, foodName, foodPrice " + 
				"from orderdetailet o left join food f on o.foodId=f.foodId " + 
				"where o.orderId = ?";
//		String sql = "select o.*, f.foodName, f.foodPrice from food f, orderdetailet o where orderId = ? and f.foodId = o.foodId";
		List<OrderDetailet> list = new ArrayList<>();
		try {
			pst = con.prepareStatement(sql);
			pst.setInt(1, orderId);
			rs = pst.executeQuery();
			
			while (rs.next()) {
				Food food = new Food();
				food.setFoodId(rs.getInt("foodId"));
				food.setFoodName(rs.getString("foodName"));
				food.setFoodPrice(rs.getDouble("foodPrice"));
				
				OrderDetailet orderDetailet = new OrderDetailet();
				orderDetailet.setFood(food);
				orderDetailet.setOrderId(rs.getInt("orderId"));
				orderDetailet.setQuantity(rs.getInt("quantity"));
				orderDetailet.setFoodId(food.getFoodId());
				
				list.add(orderDetailet);
			}
			return list;
		} finally {
			DBUtil.close(rs, pst);
		}
	}
	
}
